package com.gis3c.sys.dao.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.gis3c.sys.common.SerializableUtils;

@Repository("sessionDao")
public class SessionDao extends CachingSessionDAO {
	private static final Logger log = LoggerFactory.getLogger(SessionDao.class);
	private SqlSession sqlSession;
	
	@Override
	protected void doDelete(Session session) {
		// TODO Auto-generated method stub
		Serializable sessionId = session.getId();
		sqlSession.delete("SessionSql.deleteSession", sessionId);
	}

	@Override
	protected void doUpdate(Session session) {
		Map<String,Object> paramMap;
		if(session instanceof ValidatingSession && !((ValidatingSession)session).isValid()){
			return;
		}
		paramMap = new HashMap<>();
//		SerializableSession serializableSession = new SerializableSession();
//		serializableSession.setSessionId(session.getId());
//		serializableSession.setSession(SerializableUtils.serialize(session));
		paramMap.put("sessionId", session.getId());
		paramMap.put("session", SerializableUtils.serialize(session));
		
		sqlSession.update("SessionSql.updateSession", paramMap);
	}

	@Override
	protected Serializable doCreate(Session session) {
		Map<String,String> paramMap = new HashMap<String,String>();
		Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        
        paramMap.put("sessionId", session.getId().toString());
		paramMap.put("session", SerializableUtils.serialize(session));
        sqlSession.insert("SessionSql.insertSession", paramMap);
		return session.getId();
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		String sessionStr = null;
		Session resultSession = null;
		sessionStr = sqlSession.selectOne("SessionSql.selectSession", sessionId);

		if(sessionStr != null){
			resultSession = SerializableUtils.deserialize(sessionStr);
		}
		return resultSession;
	}
	
	@Resource(name="sqlSession")
	public void setSqlSession(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}
}

